package xyz.penghaonan.p2plib.job.operations;

import java.util.concurrent.atomic.AtomicBoolean;

import xyz.penghaonan.p2plib.utils.P2PActionListener;
import xyz.penghaonan.p2plib.P2PManager;
import xyz.penghaonan.p2plib.job.base.BaseOperation;
import xyz.penghaonan.p2plib.helper.p2phelper.WifiP2PHelper;
import xyz.penghaonan.p2plib.helper.sockethelper.ServerSocketHelper;

public class DeleteGroupOperation extends BaseOperation {
    public DeleteGroupOperation() {
    }

    @Override
    public void doOperation() {
        if (P2PManager.hasAvailableServerSocket()) {
            notifyProgress(0.2f, "释放通信管道");
            ServerSocketHelper serverSocketHelper = P2PManager.getServerSocketHelper();
            serverSocketHelper.release();
        }
        notifyProgress(0.2f, "解散群组");
        final AtomicBoolean res = new AtomicBoolean();
        WifiP2PHelper wifiP2PHelper = P2PManager.getP2PHelper();
        wifiP2PHelper.removeGroup(new P2PActionListener() {

            @Override
            public void onSuccess() {
                super.onSuccess();
                res.set(true);
                operationContinue();
            }

            @Override
            public void onFailure(int reason) {
                super.onFailure(reason);
                operationContinue();
            }
        });

        operationWait();
        setResult(Result.result(res.get(), res.get() ? "Delete group success" : "Delete group failed"));
        notifyProgress(0.2f, "解散群组" + (getResult().success ? "成功" : "失败"));
    }

    @Override
    public String getName() {
        return "解散群组";
    }
}
